import { HttpError, encryptPassword, generateRandomString, toSuccess, useTransaction } from '@sker/core';
import { AutoDevice, AutoUser } from '@sker/entities';
import { useData } from '@sker/runtime';
import { z } from 'zod';
/**
 * 账号及设备登录
 */
export default async () => {
    const input = z.object({
        username: z.string(),
        password: z.string(),
        device_uuid: z.string(),
        device_name: z.string()
    });
    const body = input.parse(useData())
    return await useTransaction(async m => {
        const user = await m.findOne(AutoUser, { where: { username: body.username } })
        if (!user) throw new HttpError(`用户不存在`)
        const password = await encryptPassword(body.password, user.salt)
        if (user.password !== password) {
            throw new HttpError(`密码错误`)
        }
        const checkDeviceName = await m.findOne(AutoDevice, { where: { device_name: body.device_name, uid: user.id } })
        if (checkDeviceName) {
            await m.update(AutoDevice, checkDeviceName.id, { device_uuid: body.device_uuid })
            return toSuccess(checkDeviceName.token)
        }
        const checkDeviceUuid = await m.findOne(AutoDevice, { where: { device_uuid: body.device_uuid, uid: user.id } })
        if (checkDeviceUuid) {
            await m.update(AutoDevice, checkDeviceUuid.id, { device_name: body.device_name })
            return toSuccess(checkDeviceUuid.token)
        }
        // create token
        const token = generateRandomString(32)
        // 插入数据库
        const autoDevice = m.create(AutoDevice, {
            uid: user.id,
            device_name: body.device_name,
            device_uuid: body.device_uuid,
            token: token
        });
        await m.save(AutoDevice, autoDevice);
        await m.update(AutoUser, user.id, { device_count: user.device_count + 1 });
        return toSuccess(token);
    })
}